<?php
namespace App\Service\Xcx\Mall;

class GoodsService extends BaseService
{
    //商品

    //分类列表
    public static function cateList()
    {
        $ary[] = ['id' => 0, 'title' => '所有'];
        $res = self::dbConn(self::$dbCate)
            ->select('id', 'title')
            ->skip(0)->take(3)
            ->get();
        if (!count($res)) return $ary;
        foreach ($res as $v) {
            $ary[] = [
                'id' => $v->id, 'title' => $v->title,
            ];
        }
        return $ary;
    }

    //列表
    public static function getList($pas)
    {
        $start = ($pas['start'] - 1) * $pas['limit'];
        $db = self::dbConn(self::$dbMallGoods)->where('del', 0);
        if ($pas['cate_id']) {
            $db = $db->where('cate_id', $pas['cate_id']);
        }
        $total = $db->count();
        $res = $db->select('id', 'title', 'cover', 'price')
            ->skip($start)->take($pas['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        foreach ($res as &$v) {
            $v->cover = file_exists($v->cover) ? env('DOMAIN') . '/' .$v->cover : '';
        }
        return self::toback(0, '', $res, $total);
    }

    //详情
    public static function getOne($id, $uid)
    {
        $res = self::dbConn(self::$dbMallGoods)->where('id', $id)
            //->select('id', 'title', 'price', 'detail')
            ->first();
        $imgs = self::dbConn(self::$dbMallGimg)->where('del', 0)->where('gid', $id)->get();
        if (isset($imgs[0]) && file_exists($imgs[0]->img)) {
            $res->imgs[] =  env('DOMAIN').'/'.$imgs[0]->img;
        }
        if (isset($imgs[1]) && file_exists($imgs[1]->img)) {
            $res->imgs[] =  env('DOMAIN').'/'.$imgs[1]->img;
        }
        if (isset($imgs[2]) && file_exists($imgs[2]->img)) {
            $res->imgs[] =  env('DOMAIN').'/'.$imgs[2]->img;
        }
        if (isset($imgs[3]) && file_exists($imgs[3]->img)) {
            $res->imgs[] =  env('DOMAIN').'/'.$imgs[3]->img;
        }
        $res->cart_num = self::dbConn(self::$dbMallCart)
            ->where('del', 0)->where('order_id', 0)
            ->where('uid', $uid)->sum('num');
        return self::toback(0, '', $res);
    }
}